package com.md.application.service;

import com.auth0.jwt.exceptions.JWTVerificationException;
import com.md.api.OauthApi;
import com.md.base.exception.ServerException;
import com.md.model.system.CommonResult;
import com.md.request.ReplacementTokenRequest;
import com.md.response.ReplacementTokenResponse;
import com.md.util.EncryptionUtils;
import com.md.util.ObjectUtil;
import com.md.util.RedisUtil;
import com.md.util.StringUtil;
import com.md.value.OauthConstants;
import com.md.value.enums.ErrorEnum;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class OauthApplicationService implements OauthApi {
  private final RedisUtil redisUtil;

  @Override
  public CommonResult<ReplacementTokenResponse> replacement(final ReplacementTokenRequest request) {
    String originalToken = request.getOriginalToken();
    if (ObjectUtil.isAllEmpty(originalToken, request.getShortToken())) {
      throw ServerException.build(ErrorEnum.UNAUTHORIZED);
    }
    if (ObjectUtil.isEmpty(originalToken)) {
      try {
        String uuid = EncryptionUtils.jwtDecrypt(request.getShortToken());
        originalToken = redisUtil.get(OauthConstants.SHORT_TOKEN_KEY + "_" + uuid);
      } catch (JWTVerificationException e) {
        throw ServerException.build(ErrorEnum.UNAUTHORIZED);
      }
    }
    if (ObjectUtil.isEmpty(originalToken)) {
      throw ServerException.build(ErrorEnum.UNAUTHORIZED);
    }
    return CommonResult.success(StringUtil.jsonToObject(EncryptionUtils.jwtDecrypt(originalToken),
      ReplacementTokenResponse.class));
  }
}
